package com.app.community.controller;

import com.app.community.exception.ErrorCodeEnum;
import com.app.community.service.AvatarService;
import com.app.community.service.PublishService;
import com.app.community.util.SnowflakeIdGenerator;
import com.wordnik.swagger.annotations.ApiOperation;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * publish页面controller
 * 2020/10/10 10:58
 **/
@Slf4j
@Controller
public class PublishController {

    @Autowired
    PublishService publishService;

    @Autowired
    AvatarService avatarService;

    @Autowired
    HttpSession httpSession;

    //   get页面时分配一个questionId,在分配OSS时需要用到，如果不发布也没有关系
    Map<String,Long> questionId = new HashMap<>();

    @GetMapping("publish")
    public String publish(Model model, HttpSession httpSession) {
        // 获取creator主键,且不允许未登录发布文章
        String userId;
        if ((userId = (String) httpSession.getAttribute("userId")) == null || userId.isEmpty()) {
            model.addAttribute("error", ErrorCodeEnum.HAVENOTLOGIN.getDescription());
            // 指定一个信号，如果为1，则不允许编辑发布
            model.addAttribute("signal", 1);
            return "common/publish";
        }

        // 添加用户头像
        model.addAttribute("avatar", avatarService.selectUserAvatar(userId));

        // 雪花算法生成ID
        SnowflakeIdGenerator idWorker = new SnowflakeIdGenerator(Calendar.getInstance().get(Calendar.DAY_OF_MONTH), 0);
        questionId.put(userId,idWorker.nextId());

        return "common/publish";
    }


    @ApiOperation("上传图片，支持多张上传")
    @ResponseBody
    @PostMapping("imgUpload")
    public String imgUpload(HttpServletRequest request) throws IOException {
//         前台传来的filename一直在改变，所以用map接收数据
        Map<String, MultipartFile> files = ((MultipartHttpServletRequest) request).getFileMap();
        String userId = (String)httpSession.getAttribute("userId");
        return publishService.imgUpload(files, questionId.get(userId));
    }


    @ApiOperation("发布一个问题，成功则返回首页")
    @PostMapping("publish")
    public String publish
            (Model model,
             @RequestParam(value = "title", required = false) String title,
             @RequestParam(value = "article", required = false) String article,
             @RequestParam(value = "summary", required = false) String summary,
             @RequestParam(value = "questionCoverPic", required = false) MultipartFile questionCoverPic) throws IOException {

        // 获取creator主键,且不允许未登录发布文章
        String userId;

        if ((userId = (String) httpSession.getAttribute("userId")) == null || userId.isEmpty()) {
            model.addAttribute("error", ErrorCodeEnum.HAVENOTLOGIN.getDescription());
            return "common/publish";
        }

//        返回时返回原先输入的内容
        model.addAttribute("title", title);
        model.addAttribute("article", article);

        if (title.length() < 4) {
            model.addAttribute("error",ErrorCodeEnum.INVALIDTITLELENGTH.getDescription());
            return "common/publish";
        }

        if (summary.length() < 8) {
            model.addAttribute("error", ErrorCodeEnum.INVALIDQUESTIONLENGTH.getDescription());
            return "common/publish";
        }

        // 获取创建时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = simpleDateFormat.format(new Date());

        model.addAttribute("title", title);
        model.addAttribute("article", article);
        model.addAttribute("creator", userId);

        // 判断是否上传了封面
        if (questionCoverPic != null && !questionCoverPic.isEmpty()) {
            publishService.publishQuestion(questionId.get(userId), title, article, userId, time, questionCoverPic, summary);
        } else {
            publishService.publishQuestion(questionId.get(userId), title, article, userId, time, summary);
        }
        // 成功上传就进行重定向
        return "redirect:index";
    }
}
